package com.xxx.sso.service;

import com.xxx.sso.base.BaseService;
import com.xxx.sso.entity.Permission;
import com.xxx.sso.repo.PermissionRepo;
import com.xxx.sso.vo.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author caiwl
 * @date 2020/5/11 15:14
 */
@Service
public class PermissionService extends BaseService<Permission> {
    @Autowired
    private PermissionRepo permissionRepo;

    public List<TreeNode> tree() {
        List<Permission> permissions = permissionRepo.findAll();
        List<TreeNode> result = buildTree(null, permissions);
        return result;
    }

    private List<TreeNode> buildTree(Long parentId, List<Permission> permissions) {
        List<TreeNode> nodes = new ArrayList<>();
        permissions.stream().forEach(permission -> {
            if (Objects.equals(parentId, permission.getParentId())) {
                TreeNode node = new TreeNode();
                node.setCode(permission.getCode());
                node.setName(permission.getName());
                node.setPath(permission.getPath());
                node.setChildren(buildTree(permission.getId(), permissions));
                nodes.add(node);
            }
        });
        return nodes;
    }

    @Override
    public JpaRepository<Permission, Long> repository() {
        return permissionRepo;
    }

}
